import { onMounted, reactive, ref, watch, computed } from "vue"
export const useTableData = (fetchMethod: HTABLE.RequestMethod, colunm: HTABLE.Columns[]) => {
    const isGetting = ref<boolean>(false)
    const innerTableData = ref<[]>()//内部用
    const pageOptions = reactive({
        currentPage: 1,
        pageSize: 10,
        total: 200
    })

    const fetchData = async () => {
        isGetting.value = true;
        const rawData = await fetchMethod();
        if (!rawData?.length) {
            innerTableData.value = rawData;
            isGetting.value = false;
            return;
        }
        const stringifiedFilterConditions = filterFromDataList.map(filterItem => ({
            index: filterItem.index,
            value: String(filterItem.value).toLowerCase()
        }));
        innerTableData.value = rawData.filter((item: any) => {
            return stringifiedFilterConditions.every(filterItem => {
                if (!filterItem.value) return true; // 如果过滤条件为空，则不过滤
                const itemValue = item[filterItem.index];
                // 如果itemValue是null或undefined，直接返回false
                if (itemValue == null) return false;
                // 将itemValue转换为字符串进行比较
                return String(itemValue).toLowerCase().includes(filterItem.value);
            });
        });
        isGetting.value = false;
    };

    const refreshData = () => {
        pageOptions.currentPage = 1;
        fetchData()
    }

    const outTableData = computed(() => {
        if (!innerTableData.value?.length)
            return []
        return innerTableData.value?.slice((pageOptions.currentPage - 1) * pageOptions.pageSize, pageOptions.currentPage * pageOptions.pageSize)
    })

    const filterFromDataList: Array<HTABLE.FilterFromDataList> = reactive(colunm.filter((item) => item.hideSearch !== true).map((item) => {
        return {
            value: '',
            name: item.name,
            index: item.index,
            searchProps: item.searchProps || { component: 'Input' }
        }
    }))

    watch(() => outTableData.value, (newVal) => {
        pageOptions.total = newVal?.length || 0
    }, { immediate: true })
    onMounted(() => {
        fetchData()
    })
    return {
        isGetting,
        pageOptions,
        outTableData,
        filterFromDataList,
        fetchData,
        refreshData,
    }
}